// @ts-nocheck
import {useEffect,useState} from 'react'

import {Modal, Form, Input, message} from 'antd'
import {createSubDistrict, modifySubDistrict} from '@/services/subDistrict'
import DistrictSelect from '@/components/Select/DistrictSelect'


const Index = (props) => {
  const [form] = Form.useForm()
  const {visible, onClose, onOk, mode, data} = props
  const [district,setDistrict] = useState(null)
  useEffect(() => {
    if (visible) {
      if (mode === 'modify') {
        setDistrict(data.district_id)
        form.setFieldsValue({
          name: data.name,
          district_id: data.district_id
        })
      }
    }
  }, [visible])
  const handleOk = () => {
    form.validateFields().then(values => {
      if (mode === 'create') {
        createSubDistrict(values).then(res => {
          if (res.status === 200) {
            message.success(res.message).then()
            onOk()
          } else {
            message.error('新建失败！').then()
          }
        })

      } else {
        modifySubDistrict({...values, subdistrict_id: data.subdistrict_id}).then(res => {
          if (res.status === 200) {
            message.success(res.message).then()
            onOk()
          } else {
            message.error('修改失败！').then()
          }
        })
      }
      form.resetFields()
    })
  }
  return (
    <Modal
      title={mode === 'create' ? '新建街道' : '修改街道'}
      maskClosable={false}
      destroyOnClose
      width={'20vw'}
      visible={visible}
      onCancel={() => {
        form.resetFields();
        onClose()
      }}
      onOk={handleOk}
    >
      <Form
        form={form}
        labelCol={{span: 6}}
        wrapperCol={{span: 16}}
        autoComplete="off"
      >
        <Form.Item
          label="街道名称"
          name="name"
          rules={[{required: true, message: '请输入街道名称！'}]}
        >
          <Input placeholder={'例：五三街道'}/>
        </Form.Item>

        <Form.Item
          label="所属区域"
          name="district_id"
          rules={[{required: true, message: '请输入所属区域！'}]}
        >
          <DistrictSelect onChange={(e) => {
            setDistrict(e)
          }} defaultValue={district}/>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default Index;
